07. Exercise: Builder

Building a Builder

Remember that "bean" class, UdacisearchClient, you worked with in previous exercises? That class has a constructor with lots of parameters. Furthermore, it's a mutable class. It's the perfect candidate for the Builder Pattern.

This should be a fairly straightforward procedure — you are going to take the UdacisearchClient class and make a Builder class for it. This will provide the following benefits:

  • UdacisearchClient will become an immuable type, which means its value does not change after it is created.
  • The builder class will emulate named parameters. Unlike the large constructor, the builder makes it harder for callers to accidentally mix up the order of the client properties.

Here's how to apply the builder pattern:

  1. First, make the UdacisearchClient constructor private instead of public.
  2. Next, make all the instance fields final and remove all the setter methods, such as UdacisearchClient#setId(int). Congratulations, UdacisearchClient is now an immutable type — but it's no good if we can't instantiate it! Don't forget to delete the default values of the fields.
  3. Give UdacisearchClient a static inner class called Builder. Give the builder class a non-final instance field corresponding to each field of UdacisearchClient.
  4. Create setter methods for all the builder's fields. Each method should return a reference to the Builder itself (i.e., this).
  5. Finally, add a UdacisearchClient.Builder#build() method that calls the now-private UdacisearchClient constructor.
  6. Try out UdacisearchClient.Builder in Main.java by constructing the client variable with the new Builder class: javac Main.java java Main

What do you think? Is the Builder easier to work with than the old UdacisearchClient constructor?

TODO List

Task List:

Task Feedback:

Nice work!

Code

If you need a code on the https://github.com/udacity.

  • userCode:

    export PATH=/data/jdk-15.0.1/bin:$PATH
    export JAVA_HOME=/data/jdk-15.0.1/bin